package com.pan.service.aspect;


import com.pan.entity.Result;
import com.pan.excep.enume.ErrorCode;
import com.pan.excep.error.ServiceException;
import com.pan.tools.ArrayTools;
import com.pan.tools.RedisTools;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Array;

@Component
@Aspect
public class CouponAspect {

    @Resource
    private RedisTools redisTools;

    @Pointcut("execution(public * com.pan.service.impl.CouponServiceImpl.insert(..))")
    public void insertCut(){}

    @Pointcut("execution(public * com.pan.service.impl.CouponServiceImpl.selectByCategoryIdOrGoodsId(java.lang.Long,java.lang.String))")
    public void selectByCategoryIdOrGoodsIdCut(){}


    @Pointcut("execution(public com.pan.entity.Result com.pan.service.impl.CouponServiceImpl.selectByNoStart(java.lang.String))")
    public void selectByNoStartCut(){}

    @Before("selectByNoStartCut()")
    public void checkAdminLogin(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames =  methodSignature.getParameterNames();
        Integer index = ArrayTools.indexOf(parameterNames,"adminTicket");
        if (index == null){
            throw new ServiceException(ErrorCode.ASPECT_ERROR);
        }
        String adminTicket = (String) args[index];
        boolean isAdmin = redisTools.exists("admin:"+adminTicket).getData();
        if (!isAdmin){
            throw new ServiceException(ErrorCode.NOT_LOGIN);
        }
    }

    @Before("selectByCategoryIdOrGoodsIdCut()")
    public void checkCategoryOrGoodsParameter(JoinPoint jp){
        Object[] args = jp.getArgs();
        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        String[] names = methodSignature.getParameterNames();
        Integer index = ArrayTools.indexOf(names,"type");
        if (index == null){
            throw new ServiceException(500,"切片找不到参数错误");
        }
        String type = (String) args[index];
        if (!type.equals("category") || !type.equals("goods")){
            throw new ServiceException(403,"参数错误type只能为goods或者category");
        }
    }

    @Before("insertCut()")
    public void insertCheckLogin(JoinPoint jp){
        String adminTicket = (String) jp.getArgs()[0];
        Result<Boolean> resultIsAdmin = redisTools.exists("admin:"+adminTicket);
        if (resultIsAdmin==null||!resultIsAdmin.getData()){
            throw new ServiceException(ErrorCode.NOT_LOGIN);
        }
    }


}
